import { getToken, setToken, removeToken } from "@/utils/auth";
import { login, getUserInfo } from "@/api/user";
import { constantRoutes } from "@/router";
import { resetRouter } from "@/router";
const state = {
  token: getToken(),
  userInfo: {}, //存储用户资料
  routes: constantRoutes, //存储用户角色
};

const mutations = {
  setToken(state, token) {
    state.token = token;
    setToken(token);
  },
  removeToken() {
    state.token = null;
    removeToken();
  },
  removeToken(state) {
    state.token = null;
    removeToken();
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo;
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]; // 将常量路由与新路由合并，更新状态中的路由信息
  },
};

const actions = {
  async login({ commit }, userInfo) {
    const token = await login(userInfo);
    commit("setToken", token);
  },
  async getUserInfo({ commit }) {
    const result = await getUserInfo();
    commit("setUserInfo", result);
    return result;
  },
  logout({ commit }) {
    commit("removeToken");
    commit("setUserInfo", {});
    resetRouter(); //重置路由，即清空路由表，重新跳转到登录页面
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
